//
//  NewsViewController.m
//  SAT_NET
//
//  Created by lanou3g on 16/3/2.
//  Copyright © 2016年 郭丹. All rights reserved.
//

#import "NewsViewController.h"
#import "RequestURl.h"
#import "CommonModel.h"
#import "PicModel.h"
#import "VideoModel.h"
#import "BaseCell.h"
#import "CommonCell.h"
#import "VideoCell.h"
#import "PicCell.h"
#import "ScrollPicModel.h"
#import <UIImageView+WebCache.h>
#import "DetailViewController.h"
#import "EditSortViewController.h"
#import "EditViewController.h"
#import <MJRefresh.h>


@interface NewsViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, strong)NSMutableArray *arrayAllData;
@property(nonatomic, strong)NSMutableArray *arrayPicData;
@property(nonatomic, assign)NSInteger urlID;
@property(nonatomic, assign)NSInteger urlPage;
@property(nonatomic, assign)NSInteger offsetOfShowV;
@property(nonatomic, assign)NSInteger offsetLast;

@end

@implementation NewsViewController

- (void)dealloc {
    [self removeObserver:self forKeyPath:@"offsetOfShowV" context:nil];
}


- (void)loadView {
//    [self setDicId:self.dicId];
    
    NSString *newsPath = [[NSBundle mainBundle] pathForResource:@"News" ofType:@"plist"];
    self.dicId = [NSMutableDictionary dictionaryWithContentsOfFile:newsPath];
#warning 保存到本地，每次读取赋值
    self.sortArray = [NSMutableArray arrayWithObjects:@"头条",@"苹果",@"手机",@"评测",@"热榜",@"电脑",@"视频",@"企业", nil];
    
    self.buttonWidth = 63;
    self.newsV = [[NewsView alloc] initWithFrame:[UIScreen mainScreen].bounds sortArray:self.sortArray buttonWidth:self.buttonWidth];
    
    self.view = self.newsV;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    NSLog(@"%s",__func__);
    
    [self addObserver:self forKeyPath:@"offsetOfShowV" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
    
    self.view.backgroundColor = [UIColor whiteColor];

    self.newsV.sortSV.delegate = self;
    self.newsV.showView.delegate = self;
    
    [self addButtonAction];
    
    [self setTableView];
    
    
    // 请求数据
    self.urlID = 0;
    self.urlPage = 1;
    
    self.offsetOfShowV = 0;
    self.offsetLast = 0;
    [self scrollAnimationWithOffsetLast:0 offsetNext:0];
    
    [self getDataWithOffset:self.offsetOfShowV upOrDown:YES];
    
    //右上角按钮
    [self.newsV.rightButton addTarget:self action:@selector(buttonAction) forControlEvents:(UIControlEventTouchUpInside)];
    
}

//- (void)refreshAction {
//    [self getDataWithOffset:self.offsetOfShowV];
//    
//}
#pragma mark 给顶部的按钮添加监听
- (void)addButtonAction {
    NSInteger i = 110;
    for (UIButton *button in self.newsV.sortSV.subviews) {
        if ([button isKindOfClass:[UIButton class]] == YES) {
            [button addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
            button.tag = i++;
        }
        if (i == 110) {
            [self buttonAction:button];
            
        }
    }
}

#pragma mark 对tableview初始化
- (void)setTableView {
    
    for (UITableView *tableView in self.newsV.showView.subviews) {
        if ([tableView isKindOfClass:[UITableView class]] == YES) {
            if (self.newsV.showView.contentOffset.x == 0) {
                tableView.delegate = self;
                tableView.dataSource = self;
            }
            
            [tableView registerNib:[UINib nibWithNibName:@"CommonCell" bundle:nil] forCellReuseIdentifier:@"common_id"];
            [tableView registerNib:[UINib nibWithNibName:@"PicCell" bundle:nil] forCellReuseIdentifier:@"pic_id"];
            [tableView registerNib:[UINib nibWithNibName:@"BaseCell" bundle:nil] forCellReuseIdentifier:@"base_id"];
            [tableView registerNib:[UINib nibWithNibName:@"VideoCell" bundle:nil] forCellReuseIdentifier:@"video_id"];
            tableView.rowHeight = UITableViewAutomaticDimension;
            tableView.estimatedRowHeight = 2;
            
            //            tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshAction)];
            //            tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshAction)];
            
            tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [self getDataWithOffset:self.offsetOfShowV upOrDown:YES];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [tableView reloadData];
                        [tableView.mj_header endRefreshing];
                    });
                });
                
            }];
            
            tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [self getDataWithOffset:self.offsetOfShowV upOrDown:NO];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [tableView reloadData];
                        [tableView.mj_footer endRefreshing];
                    });
                    
                });
            }];
        }
    }
}


// 监听触发事件
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"offsetOfShowV"] == YES) {
        if (self.offsetOfShowV == self.offsetLast) {
            return;
        }
        [self.arrayPicData removeAllObjects];
        [self.arrayAllData removeAllObjects];
        [self getDataWithOffset:self.offsetOfShowV upOrDown:YES];
    }
}


- (void)getDataWithOffset:(NSInteger )offSet upOrDown:(BOOL )upOrDown {
    
    //获取到当前显示的类别
//    NSInteger off = offSet.integerValue;
    self.urlID = [self.dicId[self.sortArray[offSet]] integerValue];
//    NSLog(@"---%ld,%ld,%@,%@",self.urlID,offSet,self.sortArray[offSet],self.dicId[self.sortArray[offSet]]);
    RequestURl *request = [[RequestURl alloc] init];
    //判断上拉还是下拉
    if (upOrDown) {
        self.urlPage = 1;//下拉刷新
    } else {
        ++self.urlPage;//上拉加载
    }
    [request requestWithUrlID:self.urlID UrlPage:self.urlPage success:^(id item0, id item1) {
        
        for (id item in item0) {
            [self.arrayAllData addObject:item];
        }
        for (id item in item1) {
            [self.arrayPicData addObject:item];
        }
        
        if ([self.newsV.showView.subviews[offSet] isKindOfClass:[UITableView class]]) {
            //修改UI,回到主线程！！！！
            dispatch_async(dispatch_get_main_queue(), ^{
                
                UITableView *tabelView = (UITableView *)self.newsV.showView.subviews[offSet];
                [self setHeadView];
                [tabelView reloadData];
            
            });
            
        }
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)setHeadView {
    NSInteger numberOfPic;
    //判断轮播图图片数目
    if (self.urlID == 0) {
        numberOfPic = 5;
    } else if (self.urlID == 74 || self.urlID == 210 || self.urlID == 300 || self.urlID == 165) {
        numberOfPic = 3;
    } else {
        numberOfPic = 0;
    }
    
    if (numberOfPic == 0 || self.arrayPicData.count == 0) {
        return;
    } else {
        
        for (int i = 0; i < numberOfPic; i ++) {
            NSInteger offset = self.newsV.showView.contentOffset.x / kScreenW;
            
            ScrollPicModel *scrollPM = self.arrayPicData[i];
            UIImageView *imageV =(UIImageView *)[self.newsV.showView.subviews[offset] viewWithTag:(offset * 100 + 300 + i)];
            [imageV sd_setImageWithURL:scrollPM.imgsrc placeholderImage:[UIImage imageNamed:@"placeholder1.jpg"]];
            
            UILabel *titleLable = (UILabel *)[self.newsV viewWithTag:(offset * 100 + 310 + i)];
            titleLable.text = scrollPM.stitle;
            titleLable.font = [UIFont systemFontOfSize:14];
            UILabel *typeLable = (UILabel *)[self.newsV viewWithTag:(offset * 100 + 320 + i)];
            typeLable.text = @" ";
            UILabel *numberLable = (UILabel *)[self.newsV viewWithTag:(offset * 100 + 330 + i)];
            numberLable.text = [NSString stringWithFormat:@"%d / %ld", i + 1, numberOfPic];
            
            // label的颜色渐变
            /*
#warning 未成功！！！
//            UIView *view = (UIView *)[self.newsV viewWithTag:1000];
//            if (scrollPM.stitle.length == 0) {
//                
//                
//                UIColor *color1 = [UIColor grayColor];
//                UIColor *color2 = [UIColor darkGrayColor];
//                UIColor *color3 = [UIColor blackColor];
//                CGPoint point1 = CGPointMake(0, 0);
//                CGPoint point2 = CGPointMake(0, 1);
//                
//                CAGradientLayer *layer = [CAGradientLayer new];
//                layer.colors = @[(__bridge id)color1.CGColor,(__bridge id)color2.CGColor,(__bridge id)color3.CGColor];
//                layer.startPoint = point1;
//                layer.endPoint = point2;
//                layer.locations = @[@0.1,@0.8];
//                layer.frame = view.frame;
//                [view.layer addSublayer:layer];
//                view.hidden = YES;
//            } else {
//                
//                UIColor *color1 = [UIColor grayColor];
//                UIColor *color2 = [UIColor darkGrayColor];
//                UIColor *color3 = [UIColor blackColor];
//                CGPoint point1 = CGPointMake(0, 0);
//                CGPoint point2 = CGPointMake(0, 1);
//                
//                CAGradientLayer *layer = [CAGradientLayer new];
//                layer.colors = @[(__bridge id)color1.CGColor,(__bridge id)color2.CGColor,(__bridge id)color3.CGColor];
//                layer.startPoint = point1;
//                layer.endPoint = point2;
//                layer.locations = @[@0.1,@0.8];
//                layer.frame = view.frame;
//                [view.layer addSublayer:layer];
//                view.hidden = NO;
//            }
            */
        }
    }
}

//tableview代理
- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arrayAllData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    id baseM = self.arrayAllData[indexPath.row];
    NSString *typeStr = [baseM valueForKey:@"type"];
    
    
    
    if ([typeStr integerValue] == 6) {
        
        //显示3张图片的cell
        PicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pic_id" forIndexPath:indexPath];
        PicModel *picM = self.arrayAllData[indexPath.row];
        cell.title.text = picM.stitle;
        //        cell.
        [cell.firstImgV sd_setImageWithURL:[NSURL URLWithString:picM.pics[0]] placeholderImage:[UIImage imageNamed:@"placeholder2.jpg"]];
        [cell.secondImgV sd_setImageWithURL:[NSURL URLWithString:picM.pics[1]] placeholderImage:[UIImage imageNamed:@"placeholder2.jpg"]];
        [cell.thirdImgV sd_setImageWithURL:[NSURL URLWithString:picM.pics[2]] placeholderImage:[UIImage imageNamed:@"placeholder2.jpg"]];
        return cell;
        
        
    }
    
    else if ([typeStr integerValue] == 9) {
        
        //视频cell
        
        VideoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"video_id" forIndexPath:indexPath];
        VideoModel *videoM = self.arrayAllData[indexPath.row];
        cell.title.text = videoM.stitle;
        [cell.imageV sd_setImageWithURL:[NSURL URLWithString:videoM.imgsrc] placeholderImage:[UIImage imageNamed:@"placeholder1.jpg"]];
        cell.time.text = [self handleDateWithDate:videoM.sdate];
        cell.type.text = videoM.tag;
        CGFloat hit = [videoM.play_count floatValue];
        if (hit < 10000) {
            cell.play_count.text = [NSString stringWithFormat:@"%.0f次播放",hit];
        } else {
            cell.play_count.text = [NSString stringWithFormat:@"%.1f万次播放",hit / 10000];
        }
        
        return cell;
        
    }
    
    else {
        CommonModel *commonM = self.arrayAllData[indexPath.row];
        // 基本cell
        if ([typeStr isEqualToString:@"0"] == YES) {
            BaseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"base_id" forIndexPath:indexPath];
            [cell.imageV sd_setImageWithURL:[NSURL URLWithString:commonM.imgsrc] placeholderImage:[UIImage imageNamed:@"placeholder1.jpg"]];
            cell.title.text = commonM.stitle;
            cell.time.text = [self handleDateWithDate:commonM.sdate];
            cell.commentNum.text = [NSString stringWithFormat:@"%ld",commonM.comment_num];
            return cell;
        } else {
            //带标签的cell
            CommonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"common_id" forIndexPath:indexPath];
            
            if ([commonM.imgsrc isEqualToString: @""] == NO) {
                [cell.imageV sd_setImageWithURL:[NSURL URLWithString:commonM.imgsrc] placeholderImage:[UIImage imageNamed:@"placeholder1.jpg"]];
            }
            
            cell.title.text = commonM.stitle;
            cell.time.text = [self handleDateWithDate:commonM.sdate];
            cell.commen_num.text = [NSString stringWithFormat:@"%ld",commonM.comment_num];
            cell.type.layer.cornerRadius = 3;
            cell.type.layer.masksToBounds = YES;
            switch ([typeStr intValue]) {
                case 2:{
                    cell.type.backgroundColor = [UIColor redColor];
                    cell.type.text = @"专题";
                    cell.commentImgV.hidden = YES;
                    cell.commen_num.hidden = YES;
                    break;
                }
                case 4:{
                    cell.type.backgroundColor = [UIColor blueColor];
                    cell.type.text = @"视频";
                    break;
                }
                case 5:{
                    cell.type.backgroundColor = [UIColor redColor];
                    cell.type.text = @"直播";
                    break;
                }
                case 10:{
                    cell.type.backgroundColor = [UIColor redColor];
                    cell.type.text = @"热帖";
                    break;
                }
                    
                case 18:{
                    cell.type.backgroundColor = [UIColor blueColor];
                    cell.type.text = @"推广";
                    cell.commentImgV.hidden = YES;
                    cell.commen_num.hidden = YES;
                    cell.time.hidden = YES;
                    break;
                }
                default:
                    break;
            }
            
            return cell;
            
        }
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DetailViewController *detailVC = [[DetailViewController alloc] init];
//    detailVC.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    CommonModel *commonM = self.arrayAllData[indexPath.row];
    detailVC.url = [NSString stringWithFormat:@"%@",commonM.url];
    [self presentViewController:detailVC animated:YES completion:nil];
    
}
#pragma mark
#pragma mark 更新分类
- (void)updateSortButton:(NSMutableArray *)arr {

    [self.newsV.sortSV removeFromSuperview];
    self.newsV.sortSV = [[sortScrollV alloc] initWithSortArray:arr buttonWidth:self.buttonWidth frame:CGRectMake(0, 0, kNewsSortW, kNewsSortH)];
    self.newsV.sortSV.contentSize = CGSizeMake(arr.count * self.buttonWidth, 64);
    [self.newsV addSubview:self.newsV.sortSV];
    
    for (int i = 0; i < arr.count; i ++) {
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
        [button setFrame:CGRectMake(i * self.buttonWidth, 20, self.buttonWidth, 44)];
        [button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [self.newsV.sortSV addSubview:button];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        button.tag = 110 + i;
    }
}

#pragma mark 右上角按钮响应事件
- (void)buttonAction {
    EditViewController *editSortVC = [[EditViewController alloc] init];
    editSortVC.arrayAddData = self.sortArray;
    editSortVC.indexToShow = self.offsetOfShowV;
//    __weak typeof(self) weakSelf = self;
    [editSortVC returnSortArray:^(NSMutableArray *arr, NSInteger sort) {
        [self updateSortButton:arr];
        [self getDataWithOffset:sort upOrDown:YES];
        self.sortArray = arr;
        self.offsetOfShowV = sort;
        [self scrollAnimationWithOffsetLast:0 offsetNext:sort];
        [self setHeadView];
    }];
    
    [self presentViewController:editSortVC animated:YES completion:nil];
}

#pragma mark 分类切换按钮响应事件
- (void)buttonAction:(UIButton *)sender {
    self.offsetOfShowV = sender.tag - 110;
    [self scrollAnimationWithOffsetLast:self.offsetLast offsetNext:self.offsetOfShowV];
    
}

#pragma mark scrollView代理
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.tag == 101) {
        return;
    }
    
    NSInteger offset = self.newsV.showView.contentOffset.x / kScreenW;
    self.offsetOfShowV = offset;
    [self scrollAnimationWithOffsetLast:self.offsetLast offsetNext:self.offsetOfShowV];
}

#pragma mark 滚动动画
- (void)scrollAnimationWithOffsetLast:(NSInteger )offsetLast offsetNext:(NSInteger )offsetNext {
    
    if (offsetNext == offsetLast) {
        if (offsetLast != 0) {
            return;
        }
        self.newsV.sortSV.subviews[0].transform = CGAffineTransformMakeScale(1.3, 1.3);
        return;
    }
    
    //1. showV
    self.newsV.showView.contentOffset = CGPointMake(offsetNext * kScreenW, 0);
    
    //2. sortV

    self.newsV.sortSV.subviews[offsetNext].transform = CGAffineTransformMakeScale(1.3, 1.3);
    self.newsV.sortSV.subviews[offsetLast].transform = CGAffineTransformMakeScale(1, 1);
    self.offsetLast = self.offsetOfShowV;
    if (self.newsV.sortSV.contentSize.width <= self.newsV.sortSV.frame.size.width) {
        // 可以全部显示，不需要滚动
        return;
    }
    
    if (offsetNext >= 0 && offsetNext < 3) {
        [UIView animateWithDuration:0.5 animations:^{
            self.newsV.sortSV.contentOffset = CGPointMake(0, 0);
        }];
    } else if (offsetNext > self.sortArray.count - 1 - 3) {
        [UIView animateWithDuration:0.5 animations:^{
            self.newsV.sortSV.contentOffset = CGPointMake(50 + (self.sortArray.count - 6) * self.buttonWidth, 0);
        }];
    } else {
        [UIView animateWithDuration:0.5 animations:^{
            self.newsV.sortSV.contentOffset = CGPointMake(50 + (offsetNext - 3) * self.buttonWidth, 0);
        }];
    }
    
}


#pragma mark 截取日期
- (NSString *)handleDateWithDate:(NSString *)date {
    
    NSString *month = [date substringWithRange:NSMakeRange(5, 2)];
    NSString *day = [date substringWithRange:NSMakeRange(8, 2)];
    
    NSString *firstMonth = [month substringToIndex:1];
    NSString *firstDay = [day substringToIndex:1];
    
    if ([firstMonth isEqualToString:@"0"] == YES) {
        month = [month substringFromIndex:1];
    }
    if ([firstDay isEqualToString:@"0"] == YES) {
        day = [day substringFromIndex:1];
    }
    
    return [NSString stringWithFormat:@"%@-%@",month,day];
}

- (NSMutableArray *)arrayAllData {
    if (!_arrayAllData) {
        _arrayAllData = [NSMutableArray array];
    }
    return _arrayAllData;
}

- (NSMutableArray *)arrayPicData {
    if (!_arrayPicData) {
        _arrayPicData = [NSMutableArray array];
    }
    return _arrayPicData;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
